from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse, JsonResponse
from rest_framework.parsers import JSONParser
# from .models import User
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from .models import User

from rest_framework.views import APIView
from rest_framework.response import Response
# Create your views here.

from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.authentication import BaseAuthentication  # 基于它
from rest_framework_jwt.authentication import BaseJSONWebTokenAuthentication # 基于它
from rest_framework.exceptions import AuthenticationFailed
# from rest_framework_jwt.authentication import jwt_decode_handler
from rest_framework_jwt.utils import jwt_decode_handler # 跟上面是一个
import jwt
from rest_framework.authentication import (
    SessionAuthentication,
    BasicAuthentication,
    TokenAuthentication
)
from .utils import MyJwtAuthentication
# from api import models



class MyView(APIView):
    authentication_classes = [JSONWebTokenAuthentication]
    permission_classes = [IsAuthenticated]
    def get(self,request,*args,**kwargs):
        # token 解析
        id = request.user.id
        mobile = request.user.mobile
        return Response('你是登录用户，你的用户id是%s,你的手机号是%s' % (id,mobile))

   # def post(self,request,*args,**kwargs):
   #      # token 解析
   #      id = request.user.id
   #      mobile = request.user.mobile
   #      return Response('你是登录用户，你的用户id是%s,你的手机号是%s' % (id,mobile))



class YourView(APIView):
    authentication_classes = [JSONWebTokenAuthentication]
    def get(self,request,*args,**kwargs):
        return Response('你是游客，你只能看这个')

class MyJwtAuthenticationView(APIView):
    authentication_classes = [MyJwtAuthentication,JSONWebTokenAuthentication] #如[JWTAuthentication]

    def get(self,request,*args,**kwargs):
        return Response('你是登录用户，你只能看这个')


from rest_framework.views import APIView
from rest_framework.viewsets import ViewSet
from . import ser

class LoginvView(ViewSet):
    def login(self,request,*args,**kwargs):
        login_ser=ser.LoginSerializers(data=request.data,context={'request':request})
        login_ser.is_valid(raise_exception=True)
        token=login_ser.context.get('token')
        return Response({'statue':100,'msg':"登录成功",'token':token,'username':login_ser.context.get("username")})


# class CreatUserView(APIView):
#     authentication_classes = []
#     def get(self,request,*args,**kwargs):
#         return Response('你是游客，你只能看这个')
from rest_framework.mixins import CreateModelMixin
from rest_framework import viewsets
from .ser import SmsSerializer
from rest_framework.response import Response
from rest_framework import status
from . import utils
from mytest.settings import APIKEY
from random import choice
from django.core.cache import cache
# from .models import VerifyCode


class SmsCodeViewset(CreateModelMixin,viewsets.GenericViewSet):
    '''
    手机验证码
    '''
    serializer_class = SmsSerializer

    def generate_code(self):
        """
        生成四位数字的验证码
        """
        seeds = "1234567890"
        random_str = []
        for i in range(4):
            random_str.append(choice(seeds))

        return "".join(random_str)

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        #验证合法
        serializer.is_valid(raise_exception=True)

        mobile = serializer.validated_data["mobile"]
        # 如果能成功 发送短信 就注释下一行
        cache.set('code', 'hell', 60) # 有效期 60秒

        yun_pian = utils.YunPian(APIKEY)
        #生成验证码
        code = self.generate_code()
        # 如果能成功 发送短信 就取消下一行的注释
        # ache.set('code', code, 60)
        cache.set

        sms_status = yun_pian.send_sms(code=code, mobile=mobile)

        if sms_status["code"] != 0:
            return Response({
                "mobile": sms_status["msg"]
            }, status=status.HTTP_400_BAD_REQUEST)
        else:
            # code_resord = VerifyCode(code=code, mobile=mobile)
            # code_resord.save()
            print("code_resord")
            return Response({
                "mobile": mobile
            }, status=status.HTTP_201_CREATED)


from rest_framework.viewsets import ModelViewSet
from rest_framework_jwt.utils import jwt_payload_handler, jwt_encode_handler


class LoginViewSet(ModelViewSet):

    def login_by_phone(self, request):

        # {"mobile": "13400666600", "code":"1234"}
        res = {}
        mobile = request.data['mobile']
        code = request.data['code']
        varityCode = cache.get('code')
        # 这里需要使用cache  就要配置 redis 或者数据库
        # 不然就只能使用session
        # varityCode = 'hell'
        try:
            user = User.objects.get(mobile=mobile)
            if code == varityCode:
                # serializer = self.get_serializer(data=request.data)
                # serializer.is_valid(raise_exception=True)
                # user = self.perform_create(serializer)
                # re_dict = serializer.data
                payload = jwt_payload_handler(user)
                res['code'] = 0
                res['msg'] = '登陆成功'
                res["token"] = jwt_encode_handler(payload)
            else:
                res['code'] = 0
                res['msg'] = '登陆失败,验证码错误'
        except User.DoesNotExist:
            if code == varityCode:
                user = User.objects.create_user(username=mobile, password='123456', mobile=mobile)
                payload = jwt_payload_handler(user)
                res['code'] = 0
                res['msg'] = '登陆成功'
                res["token"] = jwt_encode_handler(payload)
            else:
                res['code'] = 0
                res['msg'] = '登陆失败,验证码错误'
        return JsonResponse(res)
